// 封装axios网络请求工具类
import axios from 'axios'
import { $msg_e } from '../utils/msg.js'

// 授权异常代码
const login_error_code = [15,16,403,1008,1009,1014,1016];

// 网络请求公共配置
const instance = axios.create({
    timeout:5000
})

// 请求拦截器
instance.interceptors.request.use(
    config => {

        // 设置token到请求头中
        const token = localStorage.getItem('token');
        if (token) {
            config.headers['x-auth-token'] = token;  
        }  
        
        return config
    },
    error => {
        return Promise.reject(error)
    }
)


// 响应拦截器
instance.interceptors.response.use(
    response => {

        // 判断没有授权则跳转登录页面
        const { success,status,message } = response.data;
        if (!success && login_error_code.includes(status)){
            console.log('授权异常, status: ',status,', message: ', message)
            // 授权异常跳转登录页
            $msg_e(message)
            location.href('./login.html')
            return Promise.reject('授权异常');
        }

        return response
    },
    error => {
        $msg_e(error.message)
        return Promise.reject(error)
    }
)


export default instance

export const $get = (url, params) => {
    return instance.get(url, {params}).then(res => res.data)
}

export const $post = (url, params) => {
    return instance.post(url, params).then(res => res.data)
}
